<?php

declare(strict_types=1);

namespace Service\ConfigService;

use App\Model\BbcModel\ChannelWx;
use App\Model\BbcModel\Config;
use App\Model\BbcModel\ConfigChannel;
use App\Model\BbcModel\Mnuser;
use Service\BaseService;
use Service\Code\Normal;
use Service\CacheService\CacheProviderService as Cache;
use Service\ChannelWechatService\ChannelWechatService;

class ConfigService extends BaseService
{
    /**
     * 获取通用配置
     * @return array
     */
    public function getGeneralConfig()
    {
        $expressFree = $this->getConfig('express_free');
        $data = [
            'expree_free' => $expressFree['code'] == Normal::SUC ? $expressFree['data'] : ''
        ];
        return Normal::returnCode(Normal::SUC, '获取成功', $data);
    }

    /**
     * @获取配置
     * @param  string $code
     * @return array
     */
    public function getConfig($code)
    {
        if (empty($code)) {
            return Normal::returnCode(Normal::FAIL, 'expect param code');
        }
        $sid = getSID();
        $cache_key = "Config_GetConfig_{$code}_{$sid}";
        $data = Cache::getCacheByKey($cache_key);
        if (empty($data)) {
            $dataFromMysql = Config::instance()->info(['code' => $code, 'status' => 1]);
            if (empty($dataFromMysql)) {
                return Normal::returnCode(Normal::FAIL, 'config not exist');
            }
            $dataFromMysql['value'] = !empty(json_decode($data['value'])) ? json_decode($data['value']) : $data['value'];
            Cache::cacheBySetKeyValue($cache_key, $dataFromMysql, 30);
            $data = $dataFromMysql;
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $data);
    }

    /**
     * 显示模块
     * @return array
     */
    public function showModule(int $cid, int $qid, int $mnid, int $mid)
    {
        if (empty($cid) && empty($qid)) {
            return Normal::returnCode(Normal::FAIL, '请输入所属渠道id');
        }

        if (empty($cid) && !empty($qid)) {
            $cid = Mnuser::instance()->where('id', $qid)->value('pid');
        }

        $wechatOfficialAccounts = ChannelWechatService::instance()->getChannelWechatConfig($cid);
        return Normal::returnCode(Normal::SUC, '获取成功', [
            'app_id' => $wechatOfficialAccounts['data']['value']['app_id']
        ]);
    }

    /**
     * @param string $appid
     * @param int $mn_sid
     * @return array
     */
    public function getCid(string $appid, int $mnid, int $mn_sid = 0)
    {
        if ($mn_sid) {
            $cid = Mnuser::instance()->where('id', $mn_sid)->value('pid');
            if (empty($cid)) {
                return Normal::returnCode(Normal::FAIL, '店铺不存在');
            }
        } else {
            if ($mnid == 2) {
                $cid = ChannelWx::instance()->where('s_app_id', $appid)->value('cid');
            } elseif ($mnid == 4) {
                $cid = ChannelWx::instance()->where('app_id', $appid)->value('cid');
            } else {
                return Normal::returnCode(Normal::FAIL, '小程序参数错误');
            }
        }

        $codes = ['pay_way', 'member_vip_fee', 'id_img', 'show_config', 'store_switch', 'b2c_share', 'b2c_share'];
        $channelConfigs = ConfigChannel::instance()->where('cid', $cid)->whereIn('code', $codes)->get()->toArray();
        $channelConfigsMap = array_column($channelConfigs, NULL, 'code');
        $channelConfig = $this->getConfigValue($channelConfigsMap, $codes);
        return Normal::returnCode(
            Normal::SUC,
            '获取成功',
            [
                'cid' => $cid,
                'show_ticket' => config('show_ticket'),
                'pay_type' => $channelConfig['pay_type']['type'] ?? 0,
                'vip' => intval($channelConfig['member_vip_fee']['gift'] ?? 0),
                'vip_style' => intval($channelConfig['member_vip_fee']['img_style'] ?? 0),
                'vip_style_img' => $channelConfig['member_vip_fee']['img'] ?? '',
                'show_id_img' => $channelConfig['id_img']['id_pic'] ?? 0,
                'show_brand' => $channelConfig['show_config']['brand_show'] ?? 0,
                'store_switch' => (isset($channelConfig['store_switch']['switch']) && $channelConfig['store_switch']['switch'] == 1) ? 0 : 1,
                'b2c_share' => [
                    'store_title' => $channelConfig['b2c_share']['title'] ?? '',
                    'cover' => $channelConfig['b2c_share']['img'] ?? '',
                ]
            ]
        );

        return [];
    }

    /**
     * @param [type] $json
     * @param [type] $default_value
     * @return array
     */
    private function getConfigValue($configMap, $codes)
    {
        $codes = ['pay_way', 'member_vip_fee', 'store_switch', 'b2c_share', 'b2c_share'];
        $newConfigMap = [];
        foreach ($codes as $code) {
            if (isset($configMap[$code])) {
                $newConfigMap[$code] = json_decode($configMap[$code]['value'], true);
            } else {
                $newConfigMap[$code] = [];
            }
        }
        return $newConfigMap;
    }

    /**
     * 获取用户协议，隐私协议
     * @return array
     */
    public function getAgreement(int $mnid, int $cid)
    {
        $return=[
            'userAgreement'=>[
                'title'=>'用户服务协议',
                'content'=>'',
                'key' => 'user_agreement'
            ],
              'privacyAgreement'=>[
                  'title'=>'隐私权政策',
                  'content'=>'',
                  'key' => 'privacy_agreement'
              ],
              'dealAgreement' => [
                  'title'=>'跨境商品购买须知',
                  'content'=>'',
                  'key' => 'deal_agreement'
              ]
          ];
  
          $configs = ConfigChannel::instance()->whereIn('code',array_keys($return))->where([
              'cid'   => $cid,
              'status'=> 1
          ])->select()->toArray();
  
          $configsMap = array_column($configs,null,'code');
  
          foreach ($return as  $value){
              $key = $value['key'];
              if (!empty($configsMap[$key])){
                  $value = json_decode($configsMap[$key]['value']) ?? $configsMap[$key]['value'];
                  if(!empty($value)){
                      $return[$key]['content']= $value[$key.'_content'];
                  }
              }
          }
          return Normal::returnCode(Normal::SUC,'获取成功',$return);
    }
}
